package com.sepro.service.impl;

import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.xwork.StringUtils;
import org.springframework.stereotype.Service;

import com.sepro.dao.MemberDao;
import com.sepro.entity.Member;
import com.sepro.exception.InvalidParameterException;
import com.sepro.exception.MemberAlreadyExistException;
import com.sepro.exception.MemberNotExistException;
import com.sepro.exception.PasswordMatchFailedException;
import com.sepro.service.MemberService;

@Service("memberServiceImpl")
public class MemberServiceImpl extends BaseServiceImpl<Member, String> implements MemberService{

	@Resource(name="memberDaoImpl")
	private MemberDao memberDao;
	
	@Resource(name="memberDaoImpl")
	public void setMemberDao(MemberDao memberDao){
		super.setBaseDao(memberDao);
	}
	
	public Member verifyMember(String loginname, String password) 
		throws PasswordMatchFailedException, MemberNotExistException{

		List<Member> allList = getAllList();
		Iterator<Member> iter = allList.iterator();
		while(iter.hasNext()){
			Member member = iter.next();
			if(loginname.equals(member.getUsername()) || loginname.equals(member.getEmail())){
				//找到对应的用户
				if(!member.getPassword().equals(DigestUtils.md5Hex(password))){
					//密码不正确
					throw new PasswordMatchFailedException();
				}else{
					return member;
				}
			}
		}
		throw new MemberNotExistException();
	}
	
	public Boolean findMember(String username, String email){
		
		List<Member> allList = getAllList();
		Iterator<Member> iter = allList.iterator();
		while(iter.hasNext()){
			Member member = iter.next();
			if(member.getUsername().equals(username) || member.getEmail().equals(email)){
				//找到注册用户的用户名，该用户已经存在
				return true;
			}
		}
		return false;
	}
	
	public Member regist(String username, String email, String password) 
		throws MemberAlreadyExistException, InvalidParameterException{
		
		if(StringUtils.isEmpty(username) || StringUtils.isEmpty(email) || StringUtils.isEmpty(password)){
			//username, email or password can not be empty
			throw new InvalidParameterException();
		}
		if(findMember(username, email)){
			//找到注册的用户
			throw new MemberAlreadyExistException();
		}else{
			//未找到注册的用户，保存注册用户信息
			String encodedPass = DigestUtils.md5Hex(password);
			Member member = new Member();
			member.setUsername(username);
			member.setEmail(email);
			member.setPassword(encodedPass);
			
			save(member);
			return member;
		}
	}
	
}
